package online.westonline.com.westonline.adapter.constacts;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.constacts.bean.HumanList;
import com.easy.west.westclient.api.constacts.bean.PersonBean;
import com.easy.west.westclient.api.department.bean.DepartMentBean;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.model.UserInfo;
import de.hdodenhof.circleimageview.CircleImageView;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.entry.EmmmBean;
import online.westonline.com.westonline.ui.OneContactActivity;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.utils.GsonUtils;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.utils.UiUtlis;
import online.westonline.com.westonline.wedgit.DownImgView;

/**
 * 搜索适配器
 * 注意清空数据
 * Created by xiatao on 2018/8/29.
 */

public class PopConstactAndDepartEmentAdpater extends RecyclerView.Adapter<RecyclerView.ViewHolder> {



    private int DEPATMENT_TYPE = 0x1342;
    private int CONSTACTS_TYPE = 0x1515;
    private int EMPTY_TYPE = 0x1251;
    private List<Object> datas = new ArrayList<>();
    private List<PersonBean> datas_per = new ArrayList<>();
    private List<DepartMentBean> dep = new ArrayList<>();
    private String name;

    public void setDatas(List<PersonBean> datas_per, List<DepartMentBean> dep, String name) {
        this.datas_per = datas_per;
        this.name = name;
        this.dep = dep;
        this.datas.clear();
        if (dep!=null)
        {
            this.datas.addAll(dep);
        }

        if (datas_per!=null)
        {
            this.datas.addAll(datas_per);
        }

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = null;
        if (viewType == DEPATMENT_TYPE) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.department_item, parent, false);
            return new PopDpeartmentBeanViewholder(view);
        } else if (viewType == CONSTACTS_TYPE) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.constacts_item, parent, false);
            return new PopConstavtsViewHolder(view);
        } else if (viewType == EMPTY_TYPE) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty_view, parent, false);
            return new EmptyPopViewHolder(view);
        }
        return null;
    }

    @Override
    public int getItemViewType(int position) {
        if (datas.size() > 0) {
            if (datas.get(position) instanceof DepartMentBean) {
                return DEPATMENT_TYPE;
            } else {
                return CONSTACTS_TYPE;
            }
        } else {
            return EMPTY_TYPE;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof EmptyPopViewHolder) {
            EmptyPopViewHolder popViewHolder = (EmptyPopViewHolder) holder;
            popViewHolder.tvEmptyDesc.setText("没有任何消息");
        }
        if (holder instanceof PopDpeartmentBeanViewholder) {
            //判断是第一位
            final DepartMentBean departMentBean = (DepartMentBean) datas.get(position);
            final PopDpeartmentBeanViewholder popDpeartmentBeanViewholder = (PopDpeartmentBeanViewholder) holder;
            if (!TextUtils.isEmpty(name))
            {
                if (position == 0) {
                    String contentstr = "搜索到名字含有" + "\"" + name + "\"" + "的部门";
                    SpannableStringBuilder builder = new SpannableStringBuilder(contentstr);
                    builder.setSpan(new ForegroundColorSpan(UiUtlis.getColor(R.color.Event_Green)), 7, (7 + name.length()) + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    popDpeartmentBeanViewholder.tvSearchStateDesc.setText(builder);
                    popDpeartmentBeanViewholder.tvSearchStateDesc.setVisibility(View.VISIBLE);
                } else {
                    popDpeartmentBeanViewholder.tvSearchStateDesc.setVisibility(View.GONE);
                }
            }
            popDpeartmentBeanViewholder.tvState.setText("部门");
            popDpeartmentBeanViewholder.tvDepartmentTitle.setText(departMentBean.getName());
            //获取部门人员列表
            final List<PersonBean> personBeansList = CacheUtils.getInstance().getDepartMentConstacts(departMentBean.getDid() + departMentBean.getName());
            EmmmBean emmmBean = new EmmmBean();
            emmmBean.setPersonBeanList(personBeansList);
            popDpeartmentBeanViewholder.setDatas(emmmBean, popDpeartmentBeanViewholder.recyclerViewChildPeople);
            popDpeartmentBeanViewholder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (popDpeartmentBeanViewholder.imgExpand.isShow()) {
                        popDpeartmentBeanViewholder.imgExpand.show(false);
                        popDpeartmentBeanViewholder.recyclerViewChildPeople.setVisibility(View.GONE);
                    } else {
                        popDpeartmentBeanViewholder.recyclerViewChildPeople.setVisibility(View.VISIBLE);
                        //请求一下
                        getChildConstacts(departMentBean, popDpeartmentBeanViewholder);
                    }
                }
            });

        }
        if (holder instanceof PopConstavtsViewHolder) {
            final PersonBean personBean = (PersonBean) datas.get(position);
            final PopConstavtsViewHolder constavtsViewHolder = (PopConstavtsViewHolder) holder;
            if (!TextUtils.isEmpty(name))
            {
                //先判断结果是否部门
                if (dep.size() > 0) {
                    //为部门位置+1是联系人的位置
                    if (position == dep.size()) {
                        String contentstr = "搜索到关键字含有" + "\"" + name + "\"" + "的用户";
                        SpannableStringBuilder builder = new SpannableStringBuilder(contentstr);
                        builder.setSpan(new ForegroundColorSpan(UiUtlis.getColor(R.color.Event_Green)), 8, (8 + name.length()) + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        constavtsViewHolder.tvSearchStateDesc.setVisibility(View.VISIBLE);
                        constavtsViewHolder.tvSearchStateDesc.setText(builder);
                    } else {
                        constavtsViewHolder.tvSearchStateDesc.setVisibility(View.GONE);
                    }
                } else {
                    if (position == 0) {
                        String contentstr = "搜索到关键字含有" + "\"" + name + "\"" + "的用户";
                        SpannableStringBuilder builder = new SpannableStringBuilder(contentstr);
                        builder.setSpan(new ForegroundColorSpan(UiUtlis.getColor(R.color.Event_Green)), 8, (8 + name.length()) + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        constavtsViewHolder.tvSearchStateDesc.setVisibility(View.VISIBLE);
                        constavtsViewHolder.tvSearchStateDesc.setText(builder);
                    } else {
                        constavtsViewHolder.tvSearchStateDesc.setVisibility(View.GONE);
                    }
                }
            }

            constavtsViewHolder.tvFromDepartment.setText(personBean.getDepartmentDTO().getName());
            constavtsViewHolder.tvFromDepartment.setVisibility(View.VISIBLE);
            constavtsViewHolder.tvConstatsName.setText(personBean.getName());
            constavtsViewHolder.tvConstatsPhone.setText(personBean.getPhonenum()+"(手机号)");
            constavtsViewHolder.tvConstactsZuoji.setText(personBean.getTel()+"(座机号)");
            constavtsViewHolder.tvConstatsPosition.setText(personBean.getPosition());
            //头像加载警告
            //获取用户实体
            JMessageClient.getUserInfo(personBean.getAccess_token(), new GetUserInfoCallback() {
                @Override
                public void gotResult(int i, String s, UserInfo userInfo) {
                    if (i == 0) {
                        //获取头像
                        userInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                            @Override
                            public void gotResult(int i, String s, Bitmap bitmap) {
                                if (i == 0) {
                                    constavtsViewHolder.imgConstactsAvator.setImageBitmap(bitmap);
                                }
                            }
                        });
                    }
                }
            });
            constavtsViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(constavtsViewHolder.itemView.getContext(), OneContactActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", personBean);
                    intent.putExtras(bundle);
                    constavtsViewHolder.itemView.getContext().startActivity(intent);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return datas == null ? 0 : datas.size();
    }

    class PopDpeartmentBeanViewholder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_search_state_desc)
        TextView tvSearchStateDesc;
        @BindView(R.id.img_expand)
        DownImgView imgExpand;
        @BindView(R.id.tv_department_title)
        TextView tvDepartmentTitle;
        @BindView(R.id.tv_state)
        TextView tvState;
        @BindView(R.id.pro_constacts_state)
        ProgressBar proConstactsState;
        @BindView(R.id.recyclerView_child_people)
        RecyclerView recyclerViewChildPeople;

        public PopDpeartmentBeanViewholder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        /**
         * 设置数据源
         *
         * @param emmmBean
         * @param recyclerViewChildPeople
         */
        public void setDatas(EmmmBean emmmBean, RecyclerView recyclerViewChildPeople) {
            ConstactsAdapter constactsAdapter = new ConstactsAdapter();
            recyclerViewChildPeople.setLayoutManager(new LinearLayoutManager(this.itemView.getContext()));
            recyclerViewChildPeople.setAdapter(constactsAdapter);
            constactsAdapter.setDatas(emmmBean);
            constactsAdapter.notifyDataSetChanged();
        }
    }

    class PopConstavtsViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_search_state_desc)
        TextView tvSearchStateDesc;
        @BindView(R.id.img_constacts_avator)
        CircleImageView imgConstactsAvator;
        @BindView(R.id.tv_constats_name)
        TextView tvConstatsName;
        @BindView(R.id.tv_constats_phone)
        TextView tvConstatsPhone;
        @BindView(R.id.tv_constacts_zuoji)
        TextView tvConstactsZuoji;
        @BindView(R.id.tv_constats_position)
        TextView tvConstatsPosition;
        @BindView(R.id.tv_from_department)
        TextView tvFromDepartment;
        public PopConstavtsViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class EmptyPopViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_empty_desc)
        TextView tvEmptyDesc;

        public EmptyPopViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * 请求联系人列表
     *
     * @param departMent
     * @param viewHolder
     */
    private void getChildConstacts(final DepartMentBean departMent, final PopDpeartmentBeanViewholder viewHolder) {
        RequestParams params = new RequestParams(Constants.CONSTACTS_URL + departMent.getDid());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                HumanList humanList = GsonUtils.parseJSON(result, HumanList.class);
                EmmmBean emmmBean = new EmmmBean();
                emmmBean.setPersonBeanList(humanList.getData());
                //根据部门id储存
                //再更新
                CacheUtils.getInstance().saveDepartMentConstacts(departMent.getDid(), humanList.getData());
                //调用展开方法
                viewHolder.imgExpand.show(true);
                viewHolder.proConstactsState.setVisibility(View.GONE);
                //设置数据
                viewHolder.setDatas(emmmBean, viewHolder.recyclerViewChildPeople);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.showToast("网络出了点问题:" + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
